package com.zy.garbage.service.impl;

import com.zy.garbage.entity.Sort;
import com.zy.garbage.exception.CommonException;
import com.zy.garbage.form.SortForm;
import com.zy.garbage.repository.SortRepository;
import com.zy.garbage.service.SortService;
import com.zy.garbage.vo.SortVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SortServiceImpl implements SortService {

    @Autowired
    private SortRepository sortRepository;

    @Override
    public List<SortVO> findAll() {
        List<Sort> sortList = sortRepository.findAll();
        List<SortVO> sortVOList = new ArrayList<>();
        for (Sort sort : sortList) {
            SortVO sortVO = new SortVO();
            BeanUtils.copyProperties(sort,sortVO);
            sortVOList.add(sortVO);
        }
        return sortVOList;
    }

    @Override
    public SortVO findById(Integer sortId) {
        if (!sortRepository.findById(sortId).isPresent()){
            throw new CommonException(500,"该信息不存在");
        }
        Sort sort = sortRepository.findById(sortId).get();
        SortVO sortVO = new SortVO();
        BeanUtils.copyProperties(sort,sortVO);
        return sortVO;
    }

    @Override
    public SortVO save(SortForm sortForm) {
        if (sortForm.getSortId()!=null){
            throw new CommonException(500,"请检查输入信息");
        }
        if (sortForm.getSortName()==null||sortForm.getSortInfo()==null){
            throw new CommonException(500,"请检查输入信息");
        }
        Sort sort = new Sort();
        BeanUtils.copyProperties(sortForm,sort);
        Sort sort1 = sortRepository.save(sort);
        SortVO sortVO = new SortVO();
        BeanUtils.copyProperties(sort1,sortVO);
        return sortVO;
    }

    @Override
    public SortVO update(SortForm sortForm) {
        if (sortForm.getSortId()==null){
            throw new CommonException(500,"未查到该信息");
        }
        if (!sortRepository.findById(sortForm.getSortId()).isPresent()){
            throw new CommonException(500,"未查到该信息");
        }
        if (sortForm.getSortName()==null||sortForm.getSortInfo()==null){
            throw new CommonException(500,"请检查输入信息");
        }
        Sort sort = sortRepository.findById(sortForm.getSortId()).get();
        BeanUtils.copyProperties(sortForm,sort);
        sortRepository.save(sort);
        SortVO sortVO = new SortVO();
        BeanUtils.copyProperties(sort,sortVO);
        return sortVO;
    }

    @Override
    public void delete(Integer sortId) {
        if (!sortRepository.findById(sortId).isPresent()){
            throw new CommonException(500,"未查到该信息");
        }
        sortRepository.deleteById(sortId);
    }
}
